package com.ihome.android.market2.asynctask;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ihome.android.EAApp;
import com.ihome.android.academy.DetailActivity;
import com.ihome.android.http.HttpActions;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.frag.CategoryAppFragment;
import com.ihome.android.market2.frag.SearchAppFragment;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.MyProgressDialog;
import com.ihome.android.market2.view.DialogFactory.onBtnClickListener;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

/**
 * 根据关键字搜索APP
 * 
 * @author Emerson
 * 
 */
public class SearchAppTask extends AsyncTask<Bundle, Integer, Bundle> {
	private final String		TAG			= SearchAppTask.class.getSimpleName();
	private Context				context;
	private Fragment			fragment;
	
	private MyProgressDialog	progressDialog;
	private List<AppInfo>		mAppList;
	private int					mAppNum		= 0;
	private int					startIndex	= 0;
	private int					maxNum		= 0;

	public SearchAppTask(Context context, Fragment fragment) {
		this.context = context;
		this.fragment = fragment;
	}
	public SearchAppTask(Context context) {
		this.context = context;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progressDialog = MyProgressDialog.getDialog(context, context.getString(R.string.user_grabing_data));
		progressDialog.show();
		progressDialog.setCancelable(true);
		progressDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				if (SearchAppTask.this.getStatus().compareTo(AsyncTask.Status.FINISHED) != 0)
					SearchAppTask.this.cancel(true);
			}
		});
	}

	@Override
	protected Bundle doInBackground(Bundle... params) {
		Bundle b = params[0];
		int sort = b.getInt(HttpKeys.KEY_SORT);
		int charge = b.getInt(HttpKeys.KEY_CHARGE);
		startIndex = b.getInt(HttpKeys.KEY_STARTINDEX);
		maxNum = b.getInt(HttpKeys.KEY_MAXNUM);
		String keyword = b.getString(HttpKeys.KEY_KEYWORD);
		String pkgName = b.getString(HttpKeys.KEY_PACKAGENAME, "");
		LogUtil.v(TAG, " startIndex = " + startIndex + "; sort = " + sort + "; charge = " + charge+ "; pkgName = " + pkgName);

		try {
			String appinfo = new HttpActions(context).searchApp("" + startIndex, "" + maxNum, keyword, sort, charge, pkgName);
			LogUtil.v(TAG, "appinfo = " + appinfo);
			try {
				JSONArray array = new JSONArray(appinfo);
				JSONObject jsonResult = new JSONObject(array.getJSONObject(0).optString("results"));
				int code = jsonResult.optInt(HttpKeys.KEY_CODE);
				String msg = jsonResult.optString(HttpKeys.KEY_DESCRIPTION);
				if (0 != code){
					String[] msg1 = { "", "", "" , "", "app.search", "" };
					UserBehaviorLog.getInstance().writeLog(UserBehavior.SEARCHFUNCTION_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg1);
					throw new ITVException(msg, code);
				}
					

				mAppNum = jsonResult.optInt(HttpKeys.KEY_ITEMCOUNT);
				JSONArray arr = jsonResult.optJSONArray("item");
				Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
				mAppList = g.fromJson(arr.toString(), new TypeToken<List<AppInfo>>() {}.getType());

			} catch (JSONException e) {
				String[] msg1 = { "", "", "" , "", "app.search", "" };
				UserBehaviorLog.getInstance().writeLog(UserBehavior.SEARCHFUNCTION_EXCEPTION, NotifyType.TYPE_EXCEPTION, "", msg1);
				e.printStackTrace();
			}

			if (mAppList != null /* && mAppList.size() > 0 */) {
				LogUtil.v(TAG, "mAppList.size = " + mAppList.size());
			}
			else {
				cancel(true);
			}

		} catch (ITVException e) {
			String[] msg1 = { "", "", "" , "", "app.search", "" };
			UserBehaviorLog.getInstance().writeLog(UserBehavior.SEARCHFUNCTION_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg1);
			e.printStackTrace();
			LogUtil.e(TAG, e.toString());
			b.putInt(HttpKeys.KEY_CODE, e.getStatusCode());
			b.putString(HttpKeys.KEY_DESCRIPTION, e.getMessage());
		}
		return b;
	}

	@Override
	protected void onPostExecute(Bundle result) {
		super.onPostExecute(result);
		if (progressDialog != null)
			progressDialog.dismiss();

		/** 请求出错处理 */
		if (result.containsKey(HttpKeys.KEY_CODE)) {
			if(ITVException.CODE_LOGINOUT_THREE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGINOUT_ONE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_SESSIONKEY == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGIN_ONE == result.getInt(HttpKeys.KEY_CODE)){
				new DialogFactory(context).showDialog("",result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")",context.getString(R.string.dialog_ok),new onBtnClickListener() {
					
					@Override
					public void btnRightClickListener(View v) {
						// TODO Auto-generated method stub
					}
					
					@Override
					public void btnNeutralClickListener(View v) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void btnLeftClickListener(View v) {
						// TODO Auto-generated method stub
						EAApp.getApp().exitApp(true);
					}
					
					@Override
					public void btnCloseClickListener(View v) {
						// TODO Auto-generated method stub
						
					}
				});
				return;
			}
			new DialogFactory(context).showDialog(result.getString(HttpKeys.KEY_DESCRIPTION) + "("
					+ result.getInt(HttpKeys.KEY_CODE) + ")");
			return;
		}

		
		if (fragment != null && fragment instanceof SearchAppFragment) {
			if(startIndex >= maxNum){
				((SearchAppFragment) fragment).addApps(mAppList);
			}else{
				((SearchAppFragment) fragment).getAppSuccess(mAppList, mAppNum);
			}
		}
		
		if (context instanceof DetailActivity){
			String pkgName = result.getString(HttpKeys.KEY_PACKAGENAME, "");
			if(!TextUtils.isEmpty(pkgName) && mAppList.size() == 1){
				((DetailActivity) context).getAppDetail(Integer.parseInt(mAppList.get(0).getAppId()));
			}else{
				new DialogFactory(context).showDialog(context.getString(R.string.attention_error),context.getString(R.string.connect_service));
			}
		}

	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		LogUtil.i(TAG, "--> onCancelled");
		if (progressDialog != null)
			progressDialog.dismiss();

	}

}
